package com.cms.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.entity.base.BaseNav;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Entity - 导航
 *
 *
 *
 */
@SuppressWarnings("serial")
@EqualsAndHashCode(callSuper = false)
@TableName("cms_nav")
public class Nav extends BaseNav {

    /** 树路径分隔符 */
    public static final String TREE_PATH_SEPARATOR = ",";

    /**
     * 下级导航
     */
    @TableField(exist=false)
    @JSONField(serialize=false)
    private List<Nav> children;

    /**
     * 上级导航
     */
    @TableField(exist=false)
    @JSONField(serialize=false)
    private Nav parent;

    /**
     * 是否有下级导航
     */
    @TableField(exist=false)
    private Boolean hasChildren;

    /**
     * 获取下级导航
     *
     * @return 下级导航
     */
    public List<Nav> getChildren() {
        if(children == null){
            List<Map<String,Object>> maps = SqlRunner.db().selectList("select * from cms_nav where parentId={0} order by sort desc",getId());
            children = maps.stream().map(i-> JSON.parseObject(JSON.toJSONString(i), Nav.class)).collect(Collectors.toList());
        }
        return children;
    }

    /**
     * 获取上级导航
     * @return	上级导航
     */
    public Nav getParent(){
        if(parent == null){
            Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_nav where id={0}",getParentId());
            parent = JSON.parseObject(JSON.toJSONString(map), Nav.class);
        }
        return parent;
    }





    /**
     * 获取所有上级导航ID
     *
     * @return 所有上级导航ID
     */
    public Integer[] getParentIds() {
        String[] treePaths = StringUtils.split(getTreePath(), TREE_PATH_SEPARATOR);
        Integer[] result = new Integer[treePaths.length];
        for (int i = 0; i < treePaths.length; i++) {
            result[i] = Integer.valueOf(treePaths[i]);
        }
        return result;
    }



    /**
     * 设置值
     *
     */
    public void setValue() {
        if (getParentId() != null) {
            setTreePath(getParent().getTreePath() + getParent().getId() + TREE_PATH_SEPARATOR);
        } else {
            setTreePath(TREE_PATH_SEPARATOR);
        }
        setGrade(getParentIds().length);
    }

    public Boolean getHasChildren() {
        return hasChildren;
    }

    public void setHasChildren(Boolean hasChildren) {
        this.hasChildren = hasChildren;
    }
}
